package cli

import (
	"context"
	"fmt"
	"os"
)

var dbg bool

func New(cmdOpts ...Option) *Command {
	c := &Command{}
	c.Flags().SortFlags = false
	Apply(c, cmdOpts...)
	return c
}

func SetDebug(debug bool) {
	dbg = debug
}

func CheckExit(err error, printStack ...bool) {
	if err != nil {
		if dbg || (len(printStack) > 0 && printStack[0]) {
			fmt.Printf("%+v\n", err)
		} else {
			fmt.Printf("%v\n", err)
		}
		os.Exit(1)
	}
}

func (c *Command) AddTo(parent *Command) *Command {
	parent.Command.AddCommand(&c.Command)
	return parent
}

func (c *Command) Execute(ctx context.Context) {
	if err := c.Command.ExecuteContext(ctx); err != nil {
		_, _ = fmt.Fprintf(os.Stderr, err.Error())
	}
}

func (c *Command) AddCommand(commands ...*Command) {
	for _, command := range commands {
		c.Command.AddCommand(&command.Command)
	}
}
